import util from '@/utils'
// 引入接口api
import {
    delTags,
    getAssociationAttr,
    getRelationInfo,
    getAssociationInfo,
    getsubscribeTree,
    getAllTags,
    tagsSave,
    deleteOwnerTag,
    getOwnerTags,
    getExperienceInfo,
    tagsSaveOrUpdate,
    saveMonitoringInstance
} from '@/api/archives'
// 异步引入组件
const ObjSummary = () => import('./components/obj-show-summary.vue')
// 相关文档
const ObjDocument = () => import('./components/obj-show-document.vue')
// 相关多媒体
const ObjMedia = () => import('./components/obj-show-media.vue')
// 当前文档
const CurrentDoc = () => import('./components/obj-show-currentDoc.vue')
// 相关经历
const ObjExperience = () => import('./components/obj-show-experience.vue')
// 对象关系组件
const EntityGraph = () => import('./components/entity-graph.vue')
// 实体及事件添加组件
const EntityOrEventEditor = () => import('./components/entityOrEventEditor.vue')
// 文档及多媒体添加组件
const DocOrMediaEditor = () => import('./components/docOrMediaUpload.vue')
// 文档及多媒体添加组件
const TagManagement = () => import('../components/group-management.vue')
export default {
    data() {
        return {
            rowkey: '',
            objectUri: '',
            displayName: '',
            // 对象类型
            obj_type: '',
            // 对象icon
            obj_icon: '',
            // 对象类别
            obj_title: '',
            // 所属分组
            belongGroup: '',
            // 当前tab栏所在的tab
            active: 'summary',
            // 新增实体或者动态对话框是否显示
            entityOrEvent_dialog_visible: false,
            // 新增实例或事件对话框组件
            entityOrEvent_dialog: EntityOrEventEditor,
            // 新增文档或者多媒体对话框是否显示
            docOrMedia_dialog_visible: false,
            // 新增文档或者多媒体对话框
            docOrMedia_dialog: DocOrMediaEditor,
            // 新增文档或多媒体类型
            docOrMedia_add_type: 'Document',
            minHeight: 560,
            // 相关实体
            associationEntity: [],
            // 相关事件
            associationEvent: [],
            // 相关文档
            associationDocument: [],
            // 相关多媒体
            associationMedia: [],
            // 对象关系数据
            entityGraph_data: [],
            // 对象关系
            entityGraph_links: [],
            // 对象关系组件是否显示
            entityGraph_visible: false,
            // 当前所拥有的标签
            ownerTags: [],
            // 所有标签
            allTags: [],
            addTag_visible: false,
            // 当前输入的标签
            currentTag: '',
            // 过滤后的标签
            fiterTags: [],
            addTagsBox_Visible: false,
            // 教育经历数据
            education_data: [],
            // 工作经历数据
            work_data: [],
            addtagspopover: false,
            // 设置标签对话框是否展示
            setTagsDialog_Visible: false,
            // 左侧菜单树数据
            treeData: [],
            // 树节点是否展开
            expandAll_flag: true,
            // 分组弹窗是否展示
            moveDialogVisible: false,
            moveToGroup_dialog: TagManagement,
            isShowObj: true,
            // 当前多媒体model
            current_media: {
                src: '',
                type: ''
            }
        }
    },
    components: {
        ObjSummary,
        ObjExperience,
        ObjDocument,
        ObjMedia,
        CurrentDoc,
        EntityGraph,
        EntityOrEventEditor,
        DocOrMediaEditor,
        TagManagement
    },
    computed: {
        tagsCheckedList: function() {
            let a = []
            this.allTags.forEach(item => {
                if (item.isChecked) a.push(item.displayname)
            })
            return a
        }
    },
    created() {
        this.rowkey = this.$route.query.instanceUri
        this.objectUri = this.$route.query.objectUri
        this.name = this.$route.query.name
        this.displayName = this.$route.query.displayName
        this.obj_icon = this.$route.query.icon
        this.obj_type = this.$route.query.objectType
        this.belongGroup = this.$route.query.belongGroup
    },
    mounted() {
        // 防止页面后退
        window.history.pushState(null, null, document.URL)
        window.addEventListener('popstate', () => {
            window.history.pushState(null, null, document.URL)
        })
        this.getOwnerTags()
        this.init_obj()
        this.loadTree()
        if (this.obj_type == 'com.scistor.object.media') {
            this.getCurrentMedia()
            this.active = 'current_media'
        }
        if (this.obj_type == 'com.scistor.object.document') {
            this.active = 'current_document'
        }
    },
    methods: {
        // 获取当前多媒体信息
        async getCurrentMedia() {
            let data = await getAssociationAttr({ rowkey: this.rowkey, objectUri: this.objectUri })
            let proList = data.propertyList
            for (let item of proList) {
                if (item.propertyUri === 'com.scistor.property.orignaldata') {
                    this.current_media.src = item.propertyValues[0].value
                }
                if (item.propertyUri === 'com.scistor.property.documenttype') {
                    this.current_media.type = item.propertyValues[0].value.toLowerCase()
                }
            }
        },
        // 加载左侧菜单树
        loadTree() {
            getsubscribeTree().then(response => {
                this.treeData = util.parseTreeData(response.data)
            })
        },
        init_obj() {
            let obj = {
                socialaccount: '实体',
                socialdynamic: '事件',
                keyfigures: '重点人物',
                focusgroup: '重点组织',
                document: '文档',
                media: '多媒体'
            }
            let otype = obj[this.belongGroup]
            if (this.rowkey.indexOf('EVENT_WORK_EXPERIENCE') > -1) {
                otype = '工作经历'
            } else if (this.rowkey.indexOf('EVENT_EDUCATION_EXPERIENCE') > -1) {
                otype = '教育经历'
            }
            document.title = this.displayName
            this.obj_title = `${this.displayName}(${this.name})-${otype}`
        },
        // tab切换
        handlerTabClick(tab, event) {
            switch (tab.name) {
                case 'entity':
                    this.getAssociationEntity(this.rowkey)
                    break
                case 'event':
                    this.getAssociationEvent(this.rowkey)
                    break
                case 'educationExperience':
                    this.getExperienceInfo('education')
                    break
                case 'workExperience':
                    this.getExperienceInfo('work')
                    break
                case 'document':
                    this.getAssociationDoc('docuemnt')
                    break
                case 'media':
                    this.getAssociationMedia('media')
                    break
            }
        },
        // 获取相关经历
        getExperienceInfo(type) {
            let params = {
                rowkey: this.rowkey,
                experience: type
            }
            getExperienceInfo(params).then(response => {
                let data = response.data.map(item => {
                    item.timeStart = util.timestampToDate(item.experience.timeStart)
                    item.timeEnd = util.timestampToDate(item.experience.timeEnd)
                    item.experience.timeStart = util.timestampToDate(item.experience.timeStart)
                    item.experience.timeEnd = util.timestampToDate(item.experience.timeEnd)
                    return item
                })
                // 根据开始时间排序
                data = _.orderBy(data, ['timeStart'], ['desc'])
                if (type === 'education') {
                    this.education_data = data
                } else {
                    this.work_data = data
                }
            })
        },
        // 获取相关实体
        getAssociationEntity(rowkey) {
            this.entityGraph_visible = false
            // getRelationInfo
            getAssociationInfo({
                rowkey: rowkey,
                objectType: 'socialaccount',
                // objectType: 'com.scistor.object.entity',
                objecturi: this.objectUri
            }).then(response => {
                this.associationEntity = response.data
                this.associationEntity.forEach(item => {
                    if (item.personIconUrl) {
                        item.iconUrl = item.personIconUrl
                    }
                })
                let hash = {}
                const newArr = this.associationEntity.reduceRight((item, next) => {
                    hash[next.rowkey] ?
                        '' :
                        (hash[next.rowkey] = true && item.push(next))
                    return item
                }, [])
                this.associationEntity = newArr
                // this.computeEntityGraphData(this.associationEntity)
            })
            this.entityGraph_visible = true
        },
        // 获取相关实体
        getAssociationEvent(rowkey) {
            this.entityGraph_visible = false
            // getRelationInfo
            getAssociationInfo({
                rowkey: rowkey,
                objectType: 'socialdynamic',
                // objectType: 'com.scistor.object.entity',
                objecturi: this.objectUri
            }).then(response => {
                this.associationEvent = response.data
                this.associationEvent.forEach(item => {
                    if (item.personIconUrl) {
                        item.iconUrl = item.personIconUrl
                    }
                })
                let hash = {}
                const newArr = this.associationEvent.reduceRight((item, next) => {
                    hash[next.rowkey] ?
                        '' :
                        (hash[next.rowkey] = true && item.push(next))
                    return item
                }, [])
                this.associationEntity = newArr
            })
            this.entityGraph_visible = true
        },
        // 计算对象关系数据
        computeEntityGraphData(list) {
            this.entityGraph_data = []
            this.entityGraph_links = []
            if (this.associationEntity.length > 0) {
                _.forEach(this.associationEntity, array => {
                    let firstEntry = array[0]
                    let firstEntryTitle = firstEntry.showName ?
                        firstEntry.showName + '(' + firstEntry.name + ')' :
                        firstEntry.displayName + '(' + firstEntry.name + ')'
                    let secondEntry = array[1]
                    let secondEntryTitle = secondEntry.showName ?
                        secondEntry.showName + '(' + secondEntry.name + ')' :
                        secondEntry.displayName + '(' + secondEntry.name + ')'
                    // 添加对象名称数组
                    this.entityGraph_data.push({
                        name: firstEntryTitle,
                        id: firstEntry.rowkey,
                        objectType: firstEntry.objectType,
                        rowkey: firstEntry.rowkey,
                        objectUri: firstEntry.objectUri,
                        category: firstEntry.name,
                        displayName: firstEntry.showName ? firstEntry.showName : firstEntry.displayName,
                        icon: firstEntry.iconUrl,
                        belongGroup: firstEntry.belongGroup,
                        label: {
                            fontSize: firstEntry.rowkey === this.rowkey ? 16 : 12
                        }
                    })
                    this.entityGraph_data.push({
                        name: secondEntryTitle,
                        id: secondEntry.rowkey,
                        objectType: secondEntry.objectType,
                        rowkey: secondEntry.rowkey,
                        objectUri: secondEntry.objectUri,
                        category: secondEntry.name,
                        displayName: secondEntry.showName ? secondEntry.showName : secondEntry.displayName,
                        icon: secondEntry.iconUrl,
                        belongGroup: secondEntry.belongGroup,
                        label: {
                            fontSize: secondEntry.rowkey === this.rowkey ? 16 : 12
                        }
                    })
                    // 去除重复元素
                    this.entityGraph_data = _.uniqBy(this.entityGraph_data, 'rowkey')
                    if (firstEntry.path === 'from') {
                        this.entityGraph_links.push({
                            source: secondEntry.rowkey,
                            target: firstEntry.rowkey,
                            value: firstEntry.linkName,
                            lineStyle: {
                                curveness: -0.1
                            }
                        })
                    } else if (firstEntry.path === 'to') {
                        this.entityGraph_links.push({
                            source: firstEntry.rowkey,
                            target: secondEntry.rowkey,
                            value: firstEntry.linkName,
                            lineStyle: {
                                curveness: -0.1
                            }
                        })
                    } else if (firstEntry.path === 'twoway') {
                        this.entityGraph_links.push({
                            source: firstEntry.rowkey,
                            target: secondEntry.rowkey,
                            value: firstEntry.linkName,
                            lineStyle: {
                                curveness: 0
                            }
                        })
                        this.entityGraph_links.push({
                            source: secondEntry.rowkey,
                            target: firstEntry.rowkey,
                            value: firstEntry.linkName,
                            lineStyle: {
                                curveness: 0
                            }
                        })
                    }
                })
            } else {
                this.entityGraph_data.push({
                    name: this.displayName + '(' + this.name + ')',
                    objectType: this.obj_type,
                    rowkey: this.rowkey,
                    objectUri: this.objectUri,
                    category: this.name,
                    displayName: this.displayName,
                    icon: this.obj_icon,
                    belongGroup: this.belongGroup,
                    label: {
                        fontSize: 16
                    }
                })
            }
        },
        // 对象查看
        viewObjectInfo(objectType, instanceUri, objectUri, name, displayName, icon, belongGroup) {
            let currentUrl = window.location.href
            currentUrl = currentUrl.split('#')[0]
            currentUrl = `${currentUrl}#/obj-show?objectType=${objectType}&instanceUri=${instanceUri}&objectUri=${objectUri}&displayName=${displayName}&icon=${icon}&name=${name}&belongGroup=${belongGroup}`
            window.open(currentUrl, '')
        },
        // 保存监控实例
        saveMonitoringInstance() {
            let params = [{
                rowkey: this.rowkey,
                objectUri: this.objectUri
            }]
            // if (util.addToMonitoring(this.rowkey)) {
            saveMonitoringInstance(params)
                .then(response => {
                    this.$message.success('添加成功')
                })
                .catch(() => {
                    this.$message.error('已添加到监控，请勿重复添加!')
                })
            // }
        },
        // 获取相关文档
        getAssociationDoc(rowkey) {
            let param = {
                rowkey: this.rowkey,
                objectUri: this.objectUri,
                objectType: 'document'
            }
            getAssociationInfo(param).then(response => {
                this.handleFilterDoc(response.data)
            })
        },
        //  过滤文档
        handleFilterDoc(list) {
            list.forEach(item => {
                let fileName = item.showName ? item.showName : item.displayName
                let type = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length).toLowerCase()
                let fileType = {
                    txt: 'txt',
                    html: 'html',
                    doc: 'doc',
                    docx: 'doc',
                    pdf: 'pdf',
                    xls: 'excel',
                    xlsx: 'excel',
                    others: 'others'
                }
                item.fileType = fileType[type]
            })
            this.associationDocument = list
        },
        // 获取相关文档
        getAssociationMedia(rowkey) {
            let param = {
                rowkey: this.rowkey,
                objectUri: this.objectUri,
                objectType: 'media'
            }
            getAssociationInfo(param).then(response => {
                this.handleFilterMedia(response.data)
            })
        },
        // 过滤多媒体
        handleFilterMedia(list) {
            list.forEach(item => {
                let fileName = item.showName ? item.showName : item.displayName
                let type = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length).toLowerCase()
                let fileType = {
                    png: 'img',
                    gif: 'img',
                    jpg: 'img',
                    mp3: 'mp3',
                    mp4: 'mp4',
                    others: 'others'
                }
                item.fileType = fileType[type]
            })
            this.associationMedia = list
        },
        // 获取所有标签
        getAllTags() {
            getAllTags().then(response => {
                this.allTags = response.data.map(item => {
                    item.isChecked = false
                    return item
                })
                // 过滤当前对象所拥有的的标签
                this.allTags = this.allTags.filter(item => {
                    return _.indexOf(this.ownerTags, item.displayname) === -1
                })
            })
        },
        // 获取所有标签
        getOwnerTags() {
            getOwnerTags({ rowkey: this.rowkey, objecturi: this.objectUri }).then(response => {
                this.ownerTags = response.data
                this.getAllTags()
            })
        },
        // 添加标签
        addTags() {
            if (this.currentTag === '') {
                this.$message.error('请输入标签')
                return false
            }
            tagsSaveOrUpdate({
                displayname: this.currentTag
            }).then(response => {
                this.getAllTags()
                this.addTag_visible = !this.addTag_visible
                this.currentTag = ''
            })
        },
        // 关闭设置标签弹窗
        handleCloseTagsDialog() {
            this.setTagsDialog_Visible = false
        },
        // 保存标签
        saveTag(tagList) {
            let params = {
                tagList: tagList,
                rowkeyList: [{ rowkey: this.rowkey, objecturi: this.objectUri }]
            }
            tagsSave(params).then(response => {
                this.handleCloseTagsDialog()
                this.$message.success('添加成功')
                this.ownerTags.push(...tagList)
                this.getAllTags()
            })
        },
        // 设置标签
        markTags() {
            let tagList = this.allTags.filter(item => item.isChecked)
            if (tagList.length === 0) {
                this.$message.error('请选择标签')
                return false
            } else {
                this.saveTag(tagList.map(item => item.displayname))
            }
        },
        // 删除用户拥有的标签
        handleRemoveOwnerTag(tag) {
            this.$confirm('确认删除该标签?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                .then(() => {
                    util.remove(this.ownerTags, tag)
                    let params = {
                        tag: tag,
                        rowkey: this.rowkey,
                        objecturi: this.objectUri
                    }
                    deleteOwnerTag(params).then(response => {
                        this.$message.success('删除成功')
                        this.getAllTags()
                    })
                })
                .catch(() => {
                    this.$message({ type: 'info', message: '已取消删除' })
                })
        },
        // 删除全局标签
        handleRemoveTag(id) {
            this.$confirm('确认删除该标签?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                .then(() => {
                    delTags(id).then(response => {
                        this.$message.success('删除成功')
                        this.getAllTags()
                    })
                })
                .catch(() => {
                    this.$message({ type: 'info', message: '已取消删除' })
                })
        },
        // 显示新增对象对话框
        showEntityOrEventDialog(type) {
            this.entityOrEvent_dialog_visible = true
        },
        // 显示新增文档或者多媒体对话框
        showDocOrMediaDialog(type) {
            this.docOrMedia_add_type = type
            this.docOrMedia_dialog_visible = true
        },
        // 关闭新增文档或者多媒体对话框
        closeDocOrMediaDialog(data) {
            if (data.rowkey) {
                if (this.docOrMedia_add_type === 'Document') {
                    this.associationDocument.push(data)
                    this.handleFilterDoc(this.associationDocument)
                } else {
                    this.associationMedia.push(data)
                    this.handleFilterMedia(this.associationMedia)
                }
            }
            this.docOrMedia_dialog_visible = false
        }
    }
}
